#!/usr/bin/python

# Copyright 2009, 
# Fei Yu, feiyu [at] berkeley [dot] edu, 
# Jeffrey Regier, jeff [at] stat [dot] berkeley [dot] edu.
# 

# This file is part of Topics-Portal.
#
# Topics-Portal is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Topics-Portal is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with PyGrams.  If not, see <http://www.gnu.org/licenses/>.

from django import template
from django.core.urlresolvers import reverse
from django.utils.encoding import smart_unicode
from urllib import quote
import random

register = template.Library()

CLOUD_SIZE = 40

def make_tag(name):
    si = random.random() #si = size indicator
    size = u' small' if si < .1 else \
       u'' if si < .5 else u' big' if si < .85 else u' verybig'
    url = "/topics/%s" % smart_unicode(name)
    return u'<div class="%s"><a href="%s">%s</a></div>\n' % (size, url, smart_unicode(name))


#TODO: Don't use a simple_tag here...this is should be part of the view.
@register.simple_tag
def topics_cloud():
    sql = """
    select sti_topic.name 
    from sti_topic_aux, sti_topic 
    where topic_id = sti_topic.id 
    group by topic_id
    having count(*) > 2
    order by rand()
    limit %i
    """ % CLOUD_SIZE

    from django.db import connection
    cursor = connection.cursor()
    cursor.execute(sql)
    rows = cursor.fetchall()

    #TODO: Return the list of (name, size, url) tuples to the template 
    #and render them there as HTML. (Keep all the HTML in the template
    #files rather than merging it with the views.)
    tags = (make_tag(name) for name, in rows)
    return u'\n'.join(tags)

